import axios from "axios";
import { ElMessage } from "element-plus";

axios.defaults.baseURL = "/api";

axios.interceptors.request.use((config) => {
  const token = localStorage.getItem("token");
  if (token) {
    config.headers.Authorization = token;
    config.url.includes("github") &&
      (config.headers.Authorization = "token " + token);
  }
  config.timeout = 30000;
  return config;
});

axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    ElMessage.error(`${error.response.status} ${error.response.statusText}`);
    if (error.response.status === 401) {
      return false;
    } else {
      return Promise.reject(error);
    }
  }
);

export function post(url) {
  return function (params) {
    return axios
      .post(url, params)
      .then((res) => {
        return res.data;
      })
      .catch((e) => {
        console.log(e);
      });
  };
}

export function get(url) {
  return function (params = {}) {
    params.timestamp = new Date();
    return axios
      .get(url, { params })
      .then((res) => {
        return res.data;
      })
      .catch((e) => {
        console.log(e);
      });
  };
}
